####################################################-*- coding: utf-8 -*-#####
#
#
# Command line thread, singleton
#
#
##############################################################################
from threading import Thread, Lock, Event
from log import Log

class Command(Thread, BaseException):
    __single = None
    def __init__(self):
        if Command.__single:
            raise Command.__single

        Thread.__init__(self)
        Command.__single = self
        self.exit_signal = Event()
        self.signal = Event()
        self.log = Log.getInstance()

    @classmethod
    def getInstance(cls):
        try:
            single = cls()
        except cls as s:
            single = s
        return single

    def wait(self):
        """Main thread calls this to wait until current thread exit"""
        self.exit_signal.wait()

    def run(self):
        """Running while not meet exit or quit commend."""
        while True:
            cmd = input('[stock]>> ')
            cmd = cmd.lower().lstrip()   # lower case and leading space stripped
            if cmd == 'q' or cmd == 'quit':
                break
            elif cmd == '' or cmd == 'h' or cmd == 'help':
                self.printHelp()
            else:
                self.executeCommand(cmd)
        print('[stock]>> GOODBYE!')
        # inform parent threads to ending all sub thread        
        self.exit_signal.set()
        
    def printHelp(self):
        print("")
        print("  h[elp]\t show this help")
        print("  q[uit]\t quit this program")
        print("  lt\t\t list all working threads")
        print("  log \"<msg>\"\t write <msg> to log file")

    def executeCommand(self, cmd):
        if cmd == 's':
            self.signal.set()
        elif cmd[:3] == 'log':
            self.log.write('Command', cmd[3:])

